package com.wlanauth.web.action;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.wlanauth.core.criteria.GeneralCriteria;
import com.wlanauth.core.criteria.GeneralCriteriaResult;
import com.wlanauth.core.util.MD5Util;
import com.wlanauth.domain.manage.SystemProperty;
import com.wlanauth.domain.manage.User;
import com.wlanauth.service.manage.UserService;
import com.wlanauth.vo.UserVO;
import com.wlanauth.web.core.BaseActionSupport;
import com.wlanauth.web.core.JsonResult;
import com.wlanauth.web.core.SystemConstants;
import com.wlanauth.web.util.RadiusUtils;
import com.wlanauth.web.util.SystemPropertyUtils;

/**
 * 计费用户登陆验证
 * @author zz
 * @date 2012-5-9
 * @email charles.zz.life@gmail.com
 */
public class RadiusUserAction extends BaseActionSupport {

	private static final long serialVersionUID = 1L;
	
	
	private User entity;//用户实体
	
	private UserService userService;//用户服务接口
	private UserVO  radiusUserVO;//含计费信息
	
	private String userIds;//转移至历史用户或删除 ID(以,分隔);
	/**
	 * 用户登陆
	 * @return
	 */
	public String login(){
		
		if(StringUtils.isBlank(entity.getUsername())||StringUtils.isBlank(entity.getPassword())){
			this.jsonResult = new JsonResult(this,"用户名或密码不能为空",false);
			return this.actionJsonResult();
		}

		User user = userService.getByUsername(entity.getUsername());
		if(user ==null){
			this.jsonResult = new JsonResult(this,"未查询到相关用户,用户名:"+entity.getUsername(),false);
			return this.actionJsonResult();
		}
		//密码采用MD5加密
		if(MD5Util.encode(entity.getPassword()).equals(user.getPassword())){
			if(user.getExpiredTime().before(Calendar.getInstance().getTime())){
				this.jsonResult = new JsonResult(this,"很抱歉! 您的卡号已经过期. " +
						"服务有效时间至"+new SimpleDateFormat("yyyy年MM月dd日").format(user.getExpiredTime())+".",false);
				return this.actionJsonResult();
			}
			//返回部分信息至前台
			User u = new User();
			u.setActiveTime(user.getActiveTime());
			u.setAddress(user.getAddress());
			u.setBindIP(user.getBindIP());
			u.setBirth(user.getBirth());
			u.setContactPhone(user.getContactPhone());
			u.setDisplayname(user.getDisplayname());
			u.setEmail(user.getEmail());
			u.setId(user.getId());
			
			this.jsonResult = new JsonResult(this,u,true);
			this.request.getSession().setAttribute(SystemConstants.SESSION_USER_KEY, user);
		} else {
			this.jsonResult = new JsonResult(this,"密码不正确",false);
		}
		return this.actionJsonResult();
	
	}
	
	

	/**
	 * 退出
	 * @return
	 */
	public String logout(){
		User user = (User)this.request.getSession().getAttribute(SystemConstants.SESSION_USER_KEY);
		if(user == null){
			this.jsonResult = new JsonResult(this,"已退出",false);
		} else {
			this.request.getSession().setAttribute(SystemConstants.SESSION_USER_KEY, null);
			this.request.getSession().removeAttribute(SystemConstants.SESSION_USER_KEY);
			this.jsonResult = new JsonResult(this,"退出成功",true);
		}
		return this.actionJsonResult();
	}
	/**
	 * 新增
	 * @return
	 */
	public String save(){
		User temp = userService.getByBindIP(entity.getBindIP());
		if(temp != null){
			this.jsonResult = new JsonResult(this,"该IP已被绑定,IP:"+entity.getBindIP(),false);
			return this.actionJsonResult();
		}
		temp = userService.getByUsername(entity.getUsername());
		if(temp != null){
			this.jsonResult = new JsonResult(this,"该用户已存在,用户名:"+entity.getUsername(),false);
			return this.actionJsonResult();
		}
		
		entity.setStatus(User.STATUS_ENABLED);
		Calendar c = Calendar.getInstance();
		
		entity.setActiveTime(c.getTime());
		entity.setJoinTime(c.getTime());
		
//		double fee = RadiusUtils.getFee(entity.getMaxOctets());//取消计费比率
		double fee = entity.getActualFee();
		entity.setRatedFee(fee);
		entity.setActualFee(entity.getActualFee());
		entity.setPassword(MD5Util.encode(entity.getPuk()));
		
		userService.save(entity);
		
		this.jsonResult = new JsonResult(this,true);
		
		return this.actionJsonResult();
	}
	/**
	 * 更新
	 * @return
	 */
	public String update(){
		User u = this.userService.get(entity.getId());
		if(!u.getUsername().equals(entity.getUsername())){//换用户名需较验
			User temp = this.userService.getByUsername(entity.getUsername());
			if(temp!=null){
				this.jsonResult = new JsonResult(this,"该用户已存在,用户名:"+entity.getUsername(),false);
				return this.actionJsonResult();
			}
		}
		u.setUsername(entity.getUsername());
		u.setAddress(entity.getAddress());
		u.setBirth(entity.getBirth());
		u.setContactPhone(entity.getContactPhone());
		u.setDescription(entity.getDescription());
		u.setDisplayname(entity.getDisplayname());
		u.setEmail(entity.getEmail());
		u.setMaxOctets(entity.getMaxOctets());
		u.setStatus(entity.getStatus());
		u.setSexId(entity.getSexId());
		u.setUserType(entity.getUserType());
		u.setExpiredTime(entity.getExpiredTime());
		u.setPuk(entity.getPuk());
		u.setPassword(MD5Util.encode(entity.getPuk()));
//		double fee = RadiusUtils.getFee(entity.getMaxOctets());//取消计费比率
		double fee = entity.getActualFee();
		u.setRatedFee(fee);
		u.setActualFee(entity.getActualFee());
		this.userService.update(u);
		this.jsonResult = new JsonResult(this,true);
		return this.actionJsonResult();
	}
	/**
	 * 编辑
	 * @return
	 */
	public String edit(){

		UserVO vo = this.getRadiusUserVO(this.entity);
		this.jsonResult = new JsonResult(this,vo,true);
		return this.actionJsonResult();
	}
	/**
	 * 删除
	 * @return
	 */
	public String delete(){
		userService.delete(this.entity);
		this.jsonResult = new JsonResult(this,true);
		return this.actionJsonResult();
	}
	/**
	 * 批量删除
	 * @return
	 */
	public String batchDelete(){
		String[] ids = this.userIds.split(",");
		if(ids.length<1){
			this.jsonResult = new JsonResult(this,"ID不能为空",false);
			return this.actionJsonResult();
		}
		for(String id:ids){
			userService.deleteByKey(id);
			
		}
		this.jsonResult = new JsonResult(this,true);
		return this.actionJsonResult();
	}
	public String batchSwitchStatus(){
		String[] ids = this.userIds.split(",");
		if(ids.length<1){
			this.jsonResult = new JsonResult(this,"ID不能为空",false);
			return this.actionJsonResult();
		}
		for(String id:ids){
			User user = userService.get(id);
			if(!user.getStatus().equals(User.STATUS_ENABLED)){
				user.setStatus(User.STATUS_ENABLED);
			} else if(!user.getStatus().equals(User.STATUS_DISABLED)){
				user.setStatus(User.STATUS_DISABLED);
			}
			userService.update(user);
		}
		this.jsonResult = new JsonResult(this,true);
		return this.actionJsonResult();
	}
	
	/**
	 * 显示
	 * @return
	 */
	public String list(){
		SystemProperty prop = SystemPropertyUtils.getProperty(SystemPropertyUtils.KEY_OCTRULERATIO);
		double ratio = Double.parseDouble(prop.getValue());
		
		//通用查询
		GeneralCriteria criteria = this.buildWebQueryCriteria(UserVO.class);
		if(entity!=null){
			if(entity.getUsername()!=null){
				criteria.add(Restrictions.eq("username", entity.getUsername()));
			}
			if(entity.getBindIP()!=null){
				criteria.add(Restrictions.eq("bindIP", entity.getBindIP()));
			}
			if(entity.getBatchId()!=null){

				criteria.add(Restrictions.eq("batchId", entity.getBatchId()));
			}
			if(entity.getStatus()!=null){
				if(entity.getStatus().equals("NORMAL")||entity.getStatus().equals("ONLINE")){ //正常
					criteria.add(Restrictions.gt("expiredTime", new Date()));
					criteria.add(Restrictions.sqlRestriction("maxOctets*1024*1024>(sumInputOctets+sumOutputOctets)*"+ratio));
					if(entity.getStatus().equals("ONLINE")){
						criteria.add(Restrictions.isNotNull("lastAcctStartTime"));
						criteria.add(Restrictions.isNull("lastAcctStopTime"));
					}
				} else if(entity.getStatus().equals("EXPIRED")){ //过期
					criteria.add(Restrictions.lt("expiredTime", new Date()));
				} else if(entity.getStatus().equals("NONEOCT")){ //无流量
					criteria.add(Restrictions.sqlRestriction("maxOctets*1024*1024<=(sumInputOctets+sumOutputOctets)*"+ratio));
				}
			}
		}
		criteria.addOrder(Order.desc("joinTime"));
		criteria.addOrder(Order.desc("lastAcctStartTime"));
		GeneralCriteriaResult<UserVO> result = criteria.executeQuery();
		if(result.getData()!=null){
			for(UserVO vo:result.getData()){
				vo.setPassword("******");//禁止传输密码
				vo.setPuk("******");//禁止传输PUK码
				processUserVO(vo);
//				if(entity.getStatus()!=null&&!vo.getStatus().equals(User.STATUS_DISABLED)){
//					vo.setStatus(entity.getStatus());
//				}
			}
			
		}
		this.jsonResult = new JsonResult(this,result.getData(),result.getTotal());
		return this.actionJsonResult();
	}
	
	/**
	 * 转至历史用户
	 * @return
	 */
	public String moveToHis(){
		String[] ids = this.userIds.split(",");
		if(ids.length<1){
			this.jsonResult = new JsonResult(this,"ID不能为空",false);
			return this.actionJsonResult();
		}
		List<String> idList = new ArrayList<String>();
		for(String s:ids){
			idList.add(s);
		}
		this.userService.transUserToHis(idList, this.getCurrentOperator());
		this.jsonResult = new JsonResult(this,true);
		return this.actionJsonResult();
	}
	/**
	 * 取用户流量信息
	 * @return
	 */
	public String getOctetsByUserId(){
		UserVO vo = this.getRadiusUserVO(entity);
		this.jsonResult = new JsonResult(this,vo,true);
		return this.actionJsonResult();
	}
	
	
	/**
	 * 用户登陆后显示基本信息
	 * @return
	 */
	public String landedPage(){
		
		GeneralCriteria userCriteria= new GeneralCriteria(User.class);
		
		userCriteria.add(Restrictions.eq("bindIP", entity.getBindIP()));
		GeneralCriteriaResult<User> userResult = userCriteria.executeQuery();
		if(userResult.getData()== null || userResult.getData().size()<1){
			this.request.setAttribute("errorMsg", "未查询到绑定该IP的用户(IP:"+entity.getBindIP()+")");
			return SystemConstants.RESULT_USER_LOGIN;
		}
		User u = userResult.getData().get(0);
		User userCondition = new User();
		userCondition.setId(u.getId());
		radiusUserVO = this.getRadiusUserVO(userCondition);
		
		return "landedPage";
	}
	/**
	 * 显示详细信息(用于用户及操作员查看)
	 * @return
	 */
	public String viewDetailPage(){
		User userCondition = new User();
		if(entity!=null){
			userCondition.setBindIP(entity.getBindIP());
		} else {
			User u = this.getCurrentUser();
			if(u == null){
				return SystemConstants.RESULT_USER_LOGIN;
			} 
			userCondition.setId(u.getId());
		}
		
		radiusUserVO = this.getRadiusUserVO(userCondition);
		return "viewDetailPage";
		
	}
	/**
	 * 取用户（含统计流量）
	 * @param user
	 * @return
	 */
	private UserVO getRadiusUserVO(User user){
		GeneralCriteria criteria = this.buildWebQueryCriteria(UserVO.class);
		criteria.setDataOnly(true);
		if(user.getId()!=null){
			criteria.add(Restrictions.eq("id", user.getId()));
		}
		if(user.getUsername()!=null){
			criteria.add(Restrictions.eq("username", user.getUsername()));
		}
		if(user.getBindIP()!=null){
			criteria.add(Restrictions.eq("bindIP", user.getBindIP()));
		}
		
		GeneralCriteriaResult<UserVO> result = criteria.executeQuery();
		if(result.getData()==null||result.getData().size()<1) {
			return null;
		}
		UserVO u =  result.getData().get(0);
		processUserVO(u);
		return u;
		
	}
	
	
	public User getEntity() {
		return entity;
	}
	public void setEntity(User entity) {
		this.entity = entity;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public UserVO getRadiusUserVO() {
		return radiusUserVO;
	}
	
	public String getUserIds() {
		return userIds;
	}



	public void setUserIds(String userIds) {
		this.userIds = userIds;
	}


	/**
	 * 将流量数据按系统比率处理
	 * @param radiusUserVO
	 */
	protected static void processUserVO(UserVO radiusUserVO){
		//取系统属性
		
		radiusUserVO.setSumInputOctets(RadiusUtils.getViewOct(radiusUserVO.getSumInputOctets()));
		radiusUserVO.setSumOutputOctets(RadiusUtils.getViewOct(radiusUserVO.getSumOutputOctets()));
		
		BigDecimal sumOctets = RadiusUtils.getViewOct(radiusUserVO.getSumInputOctets().add(radiusUserVO.getSumOutputOctets()));
		
		double ratio = radiusUserVO.getActualFee()/(radiusUserVO.getMaxOctets()*1024);
		
		radiusUserVO.setSumFee(RadiusUtils.getFee(sumOctets.longValue(),ratio));
		
		radiusUserVO.setMaxFee(radiusUserVO.getActualFee());
		
	}
	
}
